/**
 * 全局消息提示配置，统一信息入口，方便全局调整
 * @author luguoxiang
 * @date 2022/9/18
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */

interface BaseOptions {
	/**
	 * 信息标题
	 */
	title: string;
	/**
	 * 图标
	 */
	icon?: any;
	[p: string]: any;
}

export interface ConfirmOptions extends BaseOptions {
	/**
	 * 信息内容
	 */
	message?: string;
	/**
	 * 是否开启确认框，默认：true，传入false则直接执行确认回调，不会弹窗询问用户
	 */
	enabled?: boolean;
	/**
	 * 确认按钮文字
	 */
	okText?: string;
	/**
	 * 取消按钮文字
	 */
	cancelText?: string;
}

export interface InfoOptions extends BaseOptions {
  /**
   * 延时时间
   */
  duration?: number;
}

export interface SuccessOptions extends InfoOptions {

}

export interface WarningOptions extends InfoOptions {

}

export interface ErrorOptions extends InfoOptions {

}

/**
 * 确认消息
 */
export function confirm(options: ConfirmOptions | string): Promise<any> {
  if (typeof options === 'string') {
    options = { message: options };
  } else {
    options = { ...options };
  }
  options.content = options.message;
  delete options.message;
  options.title ??= '确认您的操作';
  options.confirmText = options.okText ?? '确定';
  delete options.okText;
  options.cancelText ??= '取消';

  if (options.enabled !== false) {
    return new Promise<any>((resolve, reject) => {
      const confirm = uni.showModal({
		// @ts-ignore
        ...options,
        fail: reject,
        success: (res: { confirm: boolean; cancel: boolean; }) => {
			if (res.confirm) {
				resolve(confirm);
			} else if (res.cancel) {
				reject();
			}
        },
      });
    });
  }
  return Promise.resolve();
}

/**
 * 提示消息
 */
export function info(options: InfoOptions | string): Promise<unknown> {
  if (typeof options === 'string') {
    options = { title: options };
  }
  return uni.showToast(options);
}

/**
 * 成功消息
 */
export function success(options: SuccessOptions | string): Promise<unknown> {
  if (typeof options === 'string') {
    options = { title: options };
  }
  return uni.showToast(options);
}

/**
 * 警告消息
 */
export function warning(options: WarningOptions | string): Promise<unknown> {
  if (typeof options === 'string') {
    options = { title: options };
  }
    options.icon ??= 'error'
  return uni.showToast(options);
}

/**
 * 错误消息
 */
export function error(options: ErrorOptions | string): Promise<unknown> {
  if (typeof options === 'string') {
    options = { title: options };
  }
  options.icon ??= 'error'
  return uni.showToast(options);
}

export default {
  confirm,
  info,
  success,
  warning,
  error,
};
